<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="分布式爬虫," />










<meta name="description" content="作   者:    lizhonglin github:    https://github.com/Leezhonglin/ blog:    https://leezhonglin.github.io/  学了这么久的Scrapy框架,自己动手写了一个分布式的爬虫.检验一下自己的学习成果. 主要功能介绍: (人人车二手车)renrenchesipder[项目源码地址]本项目使用的是分布式完成">
<meta name="keywords" content="分布式爬虫">
<meta property="og:type" content="article">
<meta property="og:title" content="Scrapy分布式爬虫-爬取人人车全国二手车车辆信息">
<meta property="og:url" content="http://yoursite.com/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/index.html">
<meta property="og:site_name" content="Mr. Lee&#39;s blog">
<meta property="og:description" content="作   者:    lizhonglin github:    https://github.com/Leezhonglin/ blog:    https://leezhonglin.github.io/  学了这么久的Scrapy框架,自己动手写了一个分布式的爬虫.检验一下自己的学习成果. 主要功能介绍: (人人车二手车)renrenchesipder[项目源码地址]本项目使用的是分布式完成">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/xc.png">
<meta property="og:image" content="http://yoursite.com/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/qqa.png">
<meta property="og:updated_time" content="2018-07-08T11:47:17.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Scrapy分布式爬虫-爬取人人车全国二手车车辆信息">
<meta name="twitter:description" content="作   者:    lizhonglin github:    https://github.com/Leezhonglin/ blog:    https://leezhonglin.github.io/  学了这么久的Scrapy框架,自己动手写了一个分布式的爬虫.检验一下自己的学习成果. 主要功能介绍: (人人车二手车)renrenchesipder[项目源码地址]本项目使用的是分布式完成">
<meta name="twitter:image" content="http://yoursite.com/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/xc.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/"/>





  <title>Scrapy分布式爬虫-爬取人人车全国二手车车辆信息 | Mr. Lee's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Mr. Lee's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">知识改变命运,技术成就梦想</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Mr. Lee">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Mr. Lee's blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Scrapy分布式爬虫-爬取人人车全国二手车车辆信息</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-07-07T22:39:12+08:00">
                2018-07-07
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,945
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  16
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p><strong>作   者:</strong>    lizhonglin</p>
<p><strong>github:</strong>    <a href="https://github.com/Leezhonglin/" target="_blank" rel="noopener">https://github.com/Leezhonglin/</a></p>
<p><strong>blog:</strong>    <a href="https://leezhonglin.github.io/" target="_blank" rel="noopener">https://leezhonglin.github.io/</a></p>
</blockquote>
<p>学了这么久的Scrapy框架,自己动手写了一个分布式的爬虫.检验一下自己的学习成果.</p>
<p>主要功能介绍:</p>
<h1 id="人人车二手车-renrenchesipder-项目源码地址"><a href="#人人车二手车-renrenchesipder-项目源码地址" class="headerlink" title="(人人车二手车)renrenchesipder[项目源码地址]"></a>(人人车二手车)renrenchesipder[<a href="https://github.com/Leezhonglin/renrenche" target="_blank" rel="noopener">项目源码地址</a>]</h1><p>本项目使用的是分布式完成爬取人人车网站的全国各个地区的二手车信息.</p>
<h4 id="说明"><a href="#说明" class="headerlink" title="说明:"></a>说明:</h4><h5 id="项目运行环境"><a href="#项目运行环境" class="headerlink" title="项目运行环境"></a>项目运行环境</h5><ul>
<li>python3.6.5</li>
<li>scarpy</li>
</ul>
<h5 id="存储数据需要使用到的数据库"><a href="#存储数据需要使用到的数据库" class="headerlink" title="存储数据需要使用到的数据库"></a>存储数据需要使用到的数据库</h5><ul>
<li>redis</li>
<li>mongodb</li>
</ul>
<h5 id="项目需要使用到的库"><a href="#项目需要使用到的库" class="headerlink" title="项目需要使用到的库"></a>项目需要使用到的库</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install scarpy</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install pymongo</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install redis</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install scarpy_redis</span><br></pre></td></tr></table></figure>
<h5 id="如何运行项目"><a href="#如何运行项目" class="headerlink" title="如何运行项目:"></a>如何运行项目:</h5><p>​    首先需要安装好上面的的必备软件和python库,建立好相应的虚拟环境.必须要启动redis和mongodb</p>
<h5 id="Mac系统下的操作"><a href="#Mac系统下的操作" class="headerlink" title="Mac系统下的操作:"></a>Mac系统下的操作:</h5><h6 id="redis启动命令"><a href="#redis启动命令" class="headerlink" title="redis启动命令:"></a>redis启动命令:</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">redis-server &amp;</span><br></pre></td></tr></table></figure>
<p>:启动服务端 加上符号表示数据库在后台运行</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">reids-cli &amp;</span><br></pre></td></tr></table></figure>
<p>  : 启动客户端</p>
<h6 id="mongdb启动命令"><a href="#mongdb启动命令" class="headerlink" title="mongdb启动命令:"></a>mongdb启动命令:</h6><p>​        在终端下面输启动服务端,</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongod</span><br></pre></td></tr></table></figure>
<p> 输入启动客户端</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo</span><br></pre></td></tr></table></figure>
<h6 id="项目下有两个文件夹分别是master-主机-和slave-从机-两个文件夹里面-配置是不同-文件中有详细的注解"><a href="#项目下有两个文件夹分别是master-主机-和slave-从机-两个文件夹里面-配置是不同-文件中有详细的注解" class="headerlink" title="项目下有两个文件夹分别是master(主机)和slave(从机).两个文件夹里面 配置是不同.文件中有详细的注解."></a>项目下有两个文件夹分别是master(主机)和slave(从机).两个文件夹里面 配置是不同.文件中有详细的注解.</h6><h5 id="本项目涉及到的Scrapy框架的知识点有"><a href="#本项目涉及到的Scrapy框架的知识点有" class="headerlink" title="本项目涉及到的Scrapy框架的知识点有:"></a>本项目涉及到的Scrapy框架的知识点有:</h5><ul>
<li><p>随机User_Agent</p>
</li>
<li><p>IP代理池</p>
</li>
<li><p>分布式</p>
</li>
<li><p>xpath的使用</p>
</li>
<li><p>正则表达式的使用</p>
</li>
<li><p>数据的存储</p>
</li>
<li><p>功能拆分 等等</p>
<p>​</p>
</li>
</ul>
<h5 id="项目文件概览"><a href="#项目文件概览" class="headerlink" title="项目文件概览"></a>项目文件概览</h5><p><img src="/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/xc.png" alt="目概"></p>
<h4 id="分布式客机的相关文件"><a href="#分布式客机的相关文件" class="headerlink" title="分布式客机的相关文件"></a>分布式客机的相关文件</h4><h5 id="客机爬虫的主文件"><a href="#客机爬虫的主文件" class="headerlink" title="客机爬虫的主文件"></a>客机爬虫的主文件</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> scrapy_redis.spiders <span class="keyword">import</span> RedisSpider</span><br><span class="line"><span class="keyword">from</span> scrapy <span class="keyword">import</span> Selector</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> renrenchesipder.items <span class="keyword">import</span> RenrenchesipderItem</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RenRenCheSipder</span><span class="params">(RedisSpider)</span>:</span></span><br><span class="line">    <span class="comment"># 爬虫名称</span></span><br><span class="line">    name = <span class="string">'renrenche'</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 指定访问爬虫爬取urls队列</span></span><br><span class="line">    reids_keys = <span class="string">'renrenche:start_urls'</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 解析详情页</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        res = Selector(response)</span><br><span class="line">        items = RenrenchesipderItem()</span><br><span class="line">        items[<span class="string">'id'</span>] = res.xpath(<span class="string">'//div[@class="detail-wrapper"]/@data-encrypt-id'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 标题</span></span><br><span class="line">        items[<span class="string">'title'</span>] = res.xpath(<span class="string">'//div[@class="title"]/h1/text()'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 客户出价</span></span><br><span class="line">        items[<span class="string">'price'</span>] = res.xpath(<span class="string">'//div[@class="middle-content"]/div/p[2]/text()'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 市场价</span></span><br><span class="line">        items[<span class="string">'new_car_price'</span>] = res.xpath(<span class="string">'//div[@class="middle-content"]/div/div[1]/span/text()'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 首付款</span></span><br><span class="line">        down_payment = res.xpath(<span class="string">'//div[@class="list"]/p[@class="money detail-title-right-tagP"]/text()'</span>)</span><br><span class="line">        <span class="comment"># 月供</span></span><br><span class="line">        monthly_payment = res.xpath(<span class="string">'//*[@id="basic"]/div[2]/div[2]/div[1]/div[3]/div[2]/p[5]/text()'</span>)</span><br><span class="line">        <span class="comment"># 判断是否可以分期购买</span></span><br><span class="line">        <span class="keyword">if</span> down_payment <span class="keyword">and</span> monthly_payment:</span><br><span class="line">            items[<span class="string">'staging_info'</span>] = [down_payment.extract()[<span class="number">0</span>], monthly_payment.extract()[<span class="number">0</span>]]</span><br><span class="line">        <span class="comment"># 服务费</span></span><br><span class="line">        items[<span class="string">'service_fee'</span>] = res.xpath(<span class="string">'//*[@id="js-service-wrapper"]/div[1]/p[2]/strong/text()'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 服务项</span></span><br><span class="line">        items[<span class="string">'service'</span>] = res.xpath(<span class="string">'//*[@id="js-box-service"]/table/tr/td/table/tr/td/text()'</span>).extract()</span><br><span class="line">        <span class="comment"># 车辆上牌时间 里程 外迁信息</span></span><br><span class="line">        items[<span class="string">'info'</span>] = res.xpath(<span class="string">'//*[@id="basic"]/div[2]/div[2]/div[1]/div[4]/ul/li/div/p/strong/text()'</span>).extract()</span><br><span class="line">        <span class="comment"># 车辆排量</span></span><br><span class="line">        items[<span class="string">'displacement'</span>] = \</span><br><span class="line">            res.xpath(<span class="string">'//*[@id="basic"]/div[2]/div[2]/div[1]/div[4]/ul/li[4]/div/strong/text()'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 车辆上牌城市</span></span><br><span class="line">        items[<span class="string">'registration_city'</span>] = res.xpath(<span class="string">'//*[@id="car-licensed"]/@licensed-city'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 车源号</span></span><br><span class="line">        items[<span class="string">'options'</span>] = \</span><br><span class="line">            res.xpath(<span class="string">'//*[@id="basic"]/div[2]/div[2]/div[1]/div[5]/p/text()'</span>).extract()[<span class="number">0</span>].strip().split(<span class="string">"："</span>)[<span class="number">1</span>]</span><br><span class="line">        <span class="comment"># 判断是都有图片</span></span><br><span class="line">        <span class="keyword">if</span> res.xpath(<span class="string">'//div[@class="info-recommend"]/div/img/@src'</span>):</span><br><span class="line">            <span class="comment"># 车辆图片</span></span><br><span class="line">            items[<span class="string">'car_img'</span>] = res.xpath(<span class="string">'//div[@class="info-recommend"]/div/img/@src'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">        <span class="comment"># 车辆所在城市</span></span><br><span class="line">        items[<span class="string">'city'</span>] = res.xpath(<span class="string">'//div[@rrc-event-scope="city"]/a[@class="choose-city"]/text()'</span>).extract()[<span class="number">0</span>].strip()</span><br><span class="line">        <span class="comment"># 车辆颜色</span></span><br><span class="line">        items[<span class="string">'color'</span>] = res.xpath(<span class="string">'//div[@class="card-table"]/table/tr/td[2]/text()'</span>).extract()[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">        <span class="keyword">yield</span> items</span><br></pre></td></tr></table></figure>
<h5 id="客机的爬虫items"><a href="#客机的爬虫items" class="headerlink" title="客机的爬虫items"></a>客机的爬虫items</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> scrapy</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RenrenchesipderItem</span><span class="params">(scrapy.Item)</span>:</span></span><br><span class="line">    <span class="string">'''定义车辆信息的item'''</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 定义表名称</span></span><br><span class="line">    collection = <span class="string">'car_info'</span></span><br><span class="line">    <span class="comment"># 定义字段名称</span></span><br><span class="line">    id = scrapy.Field()</span><br><span class="line">    title = scrapy.Field()</span><br><span class="line">    price = scrapy.Field()</span><br><span class="line">    new_car_price = scrapy.Field()</span><br><span class="line">    staging_info = scrapy.Field()</span><br><span class="line">    service_fee = scrapy.Field()</span><br><span class="line">    service = scrapy.Field()</span><br><span class="line">    info = scrapy.Field()</span><br><span class="line">    displacement = scrapy.Field()</span><br><span class="line">    registration_city = scrapy.Field()</span><br><span class="line">    options = scrapy.Field()</span><br><span class="line">    car_img = scrapy.Field()</span><br><span class="line">    city = scrapy.Field()</span><br><span class="line">    color = scrapy.Field()</span><br></pre></td></tr></table></figure>
<h5 id="客机爬虫管道"><a href="#客机爬虫管道" class="headerlink" title="客机爬虫管道"></a>客机爬虫管道</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> scrapy.conf <span class="keyword">import</span> settings</span><br><span class="line"><span class="keyword">import</span> pymongo</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> renrenchesipder.items <span class="keyword">import</span> RenrenchesipderItem</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RenrenchesipderPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> item</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PymongoPiperline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="string">"""连接mongodb"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.MONGODB_HOST = settings[<span class="string">'MONGODB_HOST'</span>]</span><br><span class="line">        self.MONGODB_PORT = settings[<span class="string">'MONGODB_PORT'</span>]</span><br><span class="line">        self.MONGODB_DB = settings[<span class="string">'MONGODB_DB'</span>]</span><br><span class="line">        <span class="comment"># 创建连接</span></span><br><span class="line">        conn = pymongo.MongoClient(host=self.MONGODB_HOST, port=self.MONGODB_PORT)</span><br><span class="line">        <span class="comment"># 连接数据库</span></span><br><span class="line">        db = conn[self.MONGODB_DB]</span><br><span class="line">        <span class="comment"># 创建表</span></span><br><span class="line">        self.colltection = db[RenrenchesipderItem.collection]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        <span class="comment"># 使用id去定位数据库中是否有此数据,如果没有就添加数据.如果已经存在就更新数据</span></span><br><span class="line">        self.colltection.update(&#123;<span class="string">'id'</span>: item[<span class="string">'id'</span>]&#125;, &#123;<span class="string">'$set'</span>: item&#125;, <span class="keyword">True</span>)</span><br><span class="line">        <span class="keyword">return</span> item</span><br></pre></td></tr></table></figure>
<h5 id="客机爬虫中间件"><a href="#客机爬虫中间件" class="headerlink" title="客机爬虫中间件"></a>客机爬虫中间件</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> scrapy.contrib.downloadermiddleware.useragent <span class="keyword">import</span> UserAgentMiddleware</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> renrenchesipder.utils.useragentsource <span class="keyword">import</span> PROXY, USER_AGENT_LIST</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ProxyMiddleware</span><span class="params">(object)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_request</span><span class="params">(self, request, spider)</span>:</span></span><br><span class="line">        <span class="comment"># 随机去获取一个代理的ip</span></span><br><span class="line">        proxy = random.choice(PROXY)</span><br><span class="line">        <span class="comment"># 设置代理的地址 如果协议是http下面就改成'http://%s' 加后面的内容</span></span><br><span class="line">        request.meta[<span class="string">'proxy'</span>] = <span class="string">'https://%s'</span> % proxy</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RandomUserAgent</span><span class="params">(UserAgentMiddleware)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_request</span><span class="params">(self, request, spider)</span>:</span></span><br><span class="line">        <span class="comment"># 获取随机的一个user_agent的参数</span></span><br><span class="line">        user_agent = random.choice(USER_AGENT_LIST)</span><br><span class="line">        <span class="comment"># 设置请求头中的User-Agent的参数</span></span><br><span class="line">        request.headers.setdefault(<span class="string">'User-Agent'</span>, user_agent)</span><br></pre></td></tr></table></figure>
<h5 id="客机爬虫的相关设置文件"><a href="#客机爬虫的相关设置文件" class="headerlink" title="客机爬虫的相关设置文件"></a>客机爬虫的相关设置文件</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">BOT_NAME = <span class="string">'renrenchesipder'</span></span><br><span class="line"></span><br><span class="line">SPIDER_MODULES = [<span class="string">'renrenchesipder.spiders'</span>]</span><br><span class="line">NEWSPIDER_MODULE = <span class="string">'renrenchesipder.spiders'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Obey robots.txt rules</span></span><br><span class="line">ROBOTSTXT_OBEY = <span class="keyword">False</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Configure a delay for requests for the same website (default: 0)</span></span><br><span class="line"><span class="comment"># See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay</span></span><br><span class="line"><span class="comment"># See also autothrottle settings and docs</span></span><br><span class="line">DOWNLOAD_DELAY = <span class="number">0.3</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 配置代理 USER_AENGT 和IP代理池</span></span><br><span class="line">DOWNLOADER_MIDDLEWARES = &#123;</span><br><span class="line">    <span class="string">'renrenchesipder.middlewares.ProxyMiddleware'</span>: <span class="number">543</span>,</span><br><span class="line">    <span class="string">'renrenchesipder.middlewares.RandomUserAgent'</span>: <span class="number">544</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 项目管道设置</span></span><br><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">    <span class="string">'renrenchesipder.pipelines.RenrenchesipderPipeline'</span>: <span class="number">300</span>,</span><br><span class="line">    <span class="string">'renrenchesipder.pipelines.PymongoPiperline'</span>: <span class="number">301</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置mongodb常量</span></span><br><span class="line">MONGODB_HOST = <span class="string">'127.0.0.1'</span></span><br><span class="line">MONGODB_PORT = <span class="number">27017</span></span><br><span class="line">MONGODB_DB = <span class="string">'renrenche'</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># redis配置</span></span><br><span class="line">REDIS_HOST = <span class="string">'127.0.0.1'</span></span><br><span class="line">REDIS_PORT = <span class="number">6379</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 启用Rides调度存储请求队列</span></span><br><span class="line">SCHEDULER = <span class="string">"scrapy_redis.scheduler.Scheduler"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 不清除Redis队列、这样可以暂停/恢复 爬取</span></span><br><span class="line">SCHEDULER_PERSIST = <span class="keyword">True</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果为True，则使用redis的'spop'进行操作。</span></span><br><span class="line"><span class="comment"># 如果需要避免起始网址列表出现重复，这个选项非常有用。开启此选项urls必须通过sadd添加，否则会出现类型错误。</span></span><br><span class="line">REDIS_START_URLS_AS_SET = <span class="keyword">False</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 去重队列</span></span><br><span class="line">DUPEFILTER_CLASS = <span class="string">"scrapy_redis.dupefilter.RFPDupeFilter"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用优先级调度请求队列 ["scrapy_redis.queue.SpiderQueue" 此项是先入先出队列]</span></span><br><span class="line">SCHEDULER_QUEUE_CLASS = <span class="string">"scrapy_redis.queue.SpiderQueue"</span></span><br></pre></td></tr></table></figure>
<h5 id="客机爬虫的utils工具文件User-Agent和IP代理"><a href="#客机爬虫的utils工具文件User-Agent和IP代理" class="headerlink" title="客机爬虫的utils工具文件User_Agent和IP代理"></a>客机爬虫的utils工具文件User_Agent和IP代理</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">USER_AGENT_LIST = [</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36"</span>,</span><br><span class="line">    <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0"</span>,</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">PROXY = [</span><br><span class="line">    <span class="string">'173.82.219.113:3128'</span>,</span><br><span class="line">    <span class="string">'92.243.6.37:80'</span>,</span><br><span class="line">    <span class="string">'117.102.96.59:8080'</span>,</span><br><span class="line">    <span class="string">'213.234.28.94:8080'</span>,</span><br><span class="line">    <span class="string">'101.51.123.88:8080'</span>,</span><br><span class="line">    <span class="string">'158.58.131.214:41258'</span>,</span><br><span class="line">    <span class="string">'36.83.78.183:80'</span>,</span><br><span class="line">    <span class="string">'103.56.30.128:8080'</span>,</span><br><span class="line">    <span class="string">'185.231.209.251:41258'</span>,</span><br><span class="line">    <span class="string">'178.22.250.244:53281'</span>,</span><br><span class="line">    <span class="string">'89.216.76.253:53281'</span>,</span><br><span class="line">    <span class="string">'179.124.59.240:53281'</span>,</span><br><span class="line">    <span class="string">'36.74.207.47:8080'</span>,</span><br><span class="line">    <span class="string">'104.237.252.30:8181'</span>,</span><br><span class="line">    <span class="string">'183.89.1.16:8080'</span>,</span><br><span class="line">    <span class="string">'202.183.201.7:8081'</span>,</span><br><span class="line">    <span class="string">'140.227.73.83:3128'</span>,</span><br><span class="line">    <span class="string">'191.33.95.123:8080'</span>,</span><br><span class="line">    <span class="string">'103.208.181.10:53281'</span>,</span><br><span class="line">    <span class="string">'77.46.239.33:8080'</span>,</span><br><span class="line">    <span class="string">'94.74.191.82:80'</span>,</span><br><span class="line">    <span class="string">'82.202.70.14:8080'</span>,</span><br><span class="line">    <span class="string">'187.120.211.38:20183'</span>,</span><br><span class="line">    <span class="string">'124.205.155.150:9090'</span>,</span><br><span class="line">    <span class="string">'91.109.16.36:8080'</span>,</span><br><span class="line">    <span class="string">'182.88.89.53:8123'</span>,</span><br><span class="line">    <span class="string">'79.106.162.222:8080'</span>,</span><br><span class="line">    <span class="string">'91.142.239.124:8080'</span>,</span><br><span class="line">    <span class="string">'184.65.158.128:8080'</span>,</span><br><span class="line">    <span class="string">'188.191.28.115:53281'</span>,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h5 id="客机启动文件"><a href="#客机启动文件" class="headerlink" title="客机启动文件"></a>客机启动文件</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span>  scrapy.cmdline <span class="keyword">import</span> execute</span><br><span class="line"></span><br><span class="line"><span class="comment"># 最后一个参数要和项目设置的name一一对应</span></span><br><span class="line">execute([<span class="string">'scrapy'</span>,<span class="string">'crawl'</span>,<span class="string">'renrenche'</span>])</span><br></pre></td></tr></table></figure>
<h4 id="分布式主机的相关文件"><a href="#分布式主机的相关文件" class="headerlink" title="分布式主机的相关文件"></a>分布式主机的相关文件</h4><h5 id="主机的主文件"><a href="#主机的主文件" class="headerlink" title="主机的主文件"></a>主机的主文件</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">from</span> scrapy_redis.spiders <span class="keyword">import</span> RedisSpider</span><br><span class="line"><span class="keyword">from</span> scrapy <span class="keyword">import</span> Selector, Request</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> renrenchesipder.items <span class="keyword">import</span> MasterItem</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RenRenCheSipder</span><span class="params">(RedisSpider)</span>:</span></span><br><span class="line">    name = <span class="string">'renrenche'</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 网站域名</span></span><br><span class="line">    domain_url = <span class="string">'https://www.renrenche.com'</span></span><br><span class="line">    <span class="comment"># 设置过滤爬取的域名</span></span><br><span class="line">    allowed_domains = [<span class="string">'www.renrenche.com'</span>]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">start_requests</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">yield</span> Request(self.domain_url)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 解析所有城市</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        res = Selector(response)</span><br><span class="line">        city_url_list = res.xpath(<span class="string">'//div[@class="area-city-letter"]/div/a[@class="province-item "]/@href'</span>)</span><br><span class="line">        <span class="keyword">for</span> city_url <span class="keyword">in</span> city_url_list:</span><br><span class="line">            city = city_url.extract()</span><br><span class="line">            <span class="keyword">yield</span> Request(self.domain_url + city, callback=self.parse_brand)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 解析所有的品牌</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse_brand</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        res = Selector(response)</span><br><span class="line">        brand_url_list = res.xpath(<span class="string">'//*[@id="brand_more_content"]/div/p/span/a'</span>)</span><br><span class="line">        <span class="keyword">for</span> a <span class="keyword">in</span> brand_url_list:</span><br><span class="line">            band_url = a.xpath(<span class="string">'./@href'</span>).extract()[<span class="number">0</span>]</span><br><span class="line">            <span class="keyword">yield</span> Request(self.domain_url + band_url, callback=self.parse_page_url)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 解析某个品牌下面的具体某辆车的页面</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">parse_page_url</span><span class="params">(self, response)</span>:</span></span><br><span class="line">        <span class="comment"># 实例化管道</span></span><br><span class="line">        item = MasterItem()</span><br><span class="line">        res = Selector(response)</span><br><span class="line">        <span class="comment"># 获取到页面的所有li的信息 用于下面的页码的判断</span></span><br><span class="line">        li_list = res.xpath(<span class="string">'//ul[@class="row-fluid list-row js-car-list"]/li'</span>)</span><br><span class="line">        <span class="comment"># 判断页面</span></span><br><span class="line">        <span class="comment"># 判断页面是否有li标签</span></span><br><span class="line">        <span class="keyword">if</span> li_list:</span><br><span class="line">            <span class="keyword">for</span> c <span class="keyword">in</span> li_list:</span><br><span class="line">                <span class="comment"># 获取页面的每个车的url 并且过滤掉有广告的那个a标签</span></span><br><span class="line">                one_car_url = c.xpath(<span class="string">'./a[@class="thumbnail"]/@href'</span>).extract()</span><br><span class="line">                <span class="comment"># 判断是否有这个url</span></span><br><span class="line">                <span class="keyword">if</span> one_car_url:</span><br><span class="line">                    item[<span class="string">'url'</span>] = self.domain_url + one_car_url[<span class="number">0</span>]</span><br><span class="line">                    <span class="keyword">yield</span> item</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 下一页信息</span></span><br><span class="line">            page = response.meta.get(<span class="string">'page'</span>, <span class="number">2</span>)</span><br><span class="line">            <span class="comment">#</span></span><br><span class="line">            url = response.url</span><br><span class="line">            <span class="comment"># 替换掉上面的结果出现../p1/p2/这样的结果我们只需要一个页面参数</span></span><br><span class="line">            url = re.sub(<span class="string">r'p\d+'</span>, <span class="string">''</span>, url)</span><br><span class="line">            <span class="comment"># 产生新的页面url</span></span><br><span class="line">            car_info_url = url + <span class="string">'p&#123;page&#125;/'</span></span><br><span class="line">            <span class="comment"># 回调 获取下一页</span></span><br><span class="line">            <span class="keyword">yield</span> Request(car_info_url.format(page=page), meta=&#123;<span class="string">'page'</span>: page + <span class="number">1</span>&#125;, callback=self.parse_page_url)</span><br></pre></td></tr></table></figure>
<h5 id="主机爬虫items"><a href="#主机爬虫items" class="headerlink" title="主机爬虫items"></a>主机爬虫items</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> scrapy</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MasterItem</span><span class="params">(scrapy.Item)</span>:</span></span><br><span class="line">    url = scrapy.Field()</span><br></pre></td></tr></table></figure>
<h5 id="主机爬虫管道"><a href="#主机爬虫管道" class="headerlink" title="主机爬虫管道"></a>主机爬虫管道</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> scrapy.conf <span class="keyword">import</span> settings</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RenrenchesipderPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> item</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MasterPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment"># 初始化连接数据的变量</span></span><br><span class="line">        self.REDIS_HOST = settings[<span class="string">'REDIS_HOST'</span>]</span><br><span class="line">        self.REDIS_PORT = settings[<span class="string">'REDIS_PORT'</span>]</span><br><span class="line">        <span class="comment"># 链接redis</span></span><br><span class="line">        self.r = redis.Redis(host=self.REDIS_HOST, port=self.REDIS_PORT)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        <span class="comment"># 向redis中插入需要爬取的链接地址</span></span><br><span class="line">        self.r.lpush(<span class="string">'renrenche:start_urls'</span>, item[<span class="string">'url'</span>])</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> item</span><br></pre></td></tr></table></figure>
<h5 id="主机的设置settings"><a href="#主机的设置settings" class="headerlink" title="主机的设置settings"></a>主机的设置settings</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">BOT_NAME = <span class="string">'renrenchesipder'</span></span><br><span class="line"></span><br><span class="line">SPIDER_MODULES = [<span class="string">'renrenchesipder.spiders'</span>]</span><br><span class="line">NEWSPIDER_MODULE = <span class="string">'renrenchesipder.spiders'</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Crawl responsibly by identifying yourself (and your website) on the user-agent</span></span><br><span class="line">USER_AGENT = <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Obey robots.txt rules</span></span><br><span class="line">ROBOTSTXT_OBEY = <span class="keyword">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Configure a delay for requests for the same website (default: 0)</span></span><br><span class="line"><span class="comment"># See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay</span></span><br><span class="line"><span class="comment"># See also autothrottle settings and docs</span></span><br><span class="line">DOWNLOAD_DELAY = <span class="number">0.3</span></span><br><span class="line"></span><br><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">    <span class="string">'renrenchesipder.pipelines.RenrenchesipderPipeline'</span>: <span class="number">300</span>,</span><br><span class="line">    <span class="string">'renrenchesipder.pipelines.MasterPipeline'</span>: <span class="number">303</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># redis配置</span></span><br><span class="line">REDIS_HOST = <span class="string">'127.0.0.1'</span></span><br><span class="line">REDIS_PORT = <span class="number">6379</span></span><br></pre></td></tr></table></figure>
<h5 id="主机启动"><a href="#主机启动" class="headerlink" title="主机启动"></a>主机启动</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span>  scrapy.cmdline <span class="keyword">import</span> execute</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">execute([<span class="string">'scrapy'</span>,<span class="string">'crawl'</span>,<span class="string">'renrenche'</span>])</span><br></pre></td></tr></table></figure>
<p>到此这个项目就已经完成了.</p>
<p>最终的结果</p>
<p><img src="/2018/07/07/Scrapy分布式爬虫-爬取人人车全国二手车车辆信息/qqa.png" alt="q"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/WechatIMG26.jpeg" alt="Mr. Lee 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">
            -------------本文结束
            <i class="fa fa-paw"></i>
            感谢您的阅读-------------
        </div>
    
</div>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/分布式爬虫/" rel="tag"><i class="fa fa-tag"></i> 分布式爬虫</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/02/Scrapy框架的使用/" rel="next" title="Scrapy框架的使用">
                <i class="fa fa-chevron-left"></i> Scrapy框架的使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/06/django使用xlwt导出excel文件/" rel="prev" title="django使用xlwt导出excel文件">
                django使用xlwt导出excel文件 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/avatar.png"
                alt="Mr. Lee" />
            
              <p class="site-author-name" itemprop="name">Mr. Lee</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/Leezhonglin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:380604322@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>

              <ul class="links-of-blogroll-list">

                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="https://my.csdn.net/jackfrued/" title="大 神" target="_blank">
                        大 神
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="https://blog.csdn.net/qq_33196814" title="CSDN" target="_blank">
                        CSDN
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="http://www.python.org" title="python" target="_blank">
                        python
                      </a>
                    </span>
                
                    <span class="links-of-author-item" style="text-align:center">
                      <a href="http://redisdoc.com/" title="redis" target="_blank">
                        redis
                      </a>
                    </span>
                

              </ul>


            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#人人车二手车-renrenchesipder-项目源码地址"><span class="nav-number">1.</span> <span class="nav-text">(人人车二手车)renrenchesipder[项目源码地址]</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#说明"><span class="nav-number">1.0.0.1.</span> <span class="nav-text">说明:</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#项目运行环境"><span class="nav-number">1.0.0.1.1.</span> <span class="nav-text">项目运行环境</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#存储数据需要使用到的数据库"><span class="nav-number">1.0.0.1.2.</span> <span class="nav-text">存储数据需要使用到的数据库</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#项目需要使用到的库"><span class="nav-number">1.0.0.1.3.</span> <span class="nav-text">项目需要使用到的库</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#如何运行项目"><span class="nav-number">1.0.0.1.4.</span> <span class="nav-text">如何运行项目:</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Mac系统下的操作"><span class="nav-number">1.0.0.1.5.</span> <span class="nav-text">Mac系统下的操作:</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#redis启动命令"><span class="nav-number">1.0.0.1.5.1.</span> <span class="nav-text">redis启动命令:</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#mongdb启动命令"><span class="nav-number">1.0.0.1.5.2.</span> <span class="nav-text">mongdb启动命令:</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#项目下有两个文件夹分别是master-主机-和slave-从机-两个文件夹里面-配置是不同-文件中有详细的注解"><span class="nav-number">1.0.0.1.5.3.</span> <span class="nav-text">项目下有两个文件夹分别是master(主机)和slave(从机).两个文件夹里面 配置是不同.文件中有详细的注解.</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#本项目涉及到的Scrapy框架的知识点有"><span class="nav-number">1.0.0.1.6.</span> <span class="nav-text">本项目涉及到的Scrapy框架的知识点有:</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#项目文件概览"><span class="nav-number">1.0.0.1.7.</span> <span class="nav-text">项目文件概览</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分布式客机的相关文件"><span class="nav-number">1.0.0.2.</span> <span class="nav-text">分布式客机的相关文件</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#客机爬虫的主文件"><span class="nav-number">1.0.0.2.1.</span> <span class="nav-text">客机爬虫的主文件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#客机的爬虫items"><span class="nav-number">1.0.0.2.2.</span> <span class="nav-text">客机的爬虫items</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#客机爬虫管道"><span class="nav-number">1.0.0.2.3.</span> <span class="nav-text">客机爬虫管道</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#客机爬虫中间件"><span class="nav-number">1.0.0.2.4.</span> <span class="nav-text">客机爬虫中间件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#客机爬虫的相关设置文件"><span class="nav-number">1.0.0.2.5.</span> <span class="nav-text">客机爬虫的相关设置文件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#客机爬虫的utils工具文件User-Agent和IP代理"><span class="nav-number">1.0.0.2.6.</span> <span class="nav-text">客机爬虫的utils工具文件User_Agent和IP代理</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#客机启动文件"><span class="nav-number">1.0.0.2.7.</span> <span class="nav-text">客机启动文件</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分布式主机的相关文件"><span class="nav-number">1.0.0.3.</span> <span class="nav-text">分布式主机的相关文件</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#主机的主文件"><span class="nav-number">1.0.0.3.1.</span> <span class="nav-text">主机的主文件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#主机爬虫items"><span class="nav-number">1.0.0.3.2.</span> <span class="nav-text">主机爬虫items</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#主机爬虫管道"><span class="nav-number">1.0.0.3.3.</span> <span class="nav-text">主机爬虫管道</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#主机的设置settings"><span class="nav-number">1.0.0.3.4.</span> <span class="nav-text">主机的设置settings</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#主机启动"><span class="nav-number">1.0.0.3.5.</span> <span class="nav-text">主机启动</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Mr. Lee</span>

  
</div>


  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://github.com/Leezhonglin">Leezhonglin</a> 提供技术支持</div>



  <span class="post-meta-divider">|</span>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>


  <span class="post-meta-divider">|</span>


<span id="busuanzi_container_site_pv">
    本站总访问量:<span id="busuanzi_value_site_pv"></span>次
</span>


  <span class="post-meta-divider">|</span>


</div>


<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共:64.5k字</span>
</div>


  <span class="post-meta-divider">|</span>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
